package leetcode;

import java.util.Arrays;

/**
 * @author ht
 * @create 2025-06-18 21:03
 * @desc
 **/
public class T977 {

    /**
     * 先计算平方数，在进行排序的写法，复杂度较高
     * @param nums
     * @return
     */
    public int[] sortedSquares(int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            nums[i] = nums[i] * nums[i];
        }
        Arrays.sort(nums);
        return nums;
    }

    /**
     * 左右指针写法
     * @param nums
     * @return
     */
    public int[] sortedSquares2(int[] nums) {
        int left = 0;
        int right = nums.length - 1;

        int[] arr = new int[nums.length];
        int i = 0;
        while (left <= right) {
            i ++;
            int leftNum = nums[left] * nums[left];
            int rightNum = nums[right] * nums[right];
            if(leftNum >= rightNum) {
                arr[nums.length - i] = leftNum;
                left++;
            } else {
                arr[nums.length - i] = rightNum;
                right--;
            }
        }
        return arr;
    }
}
